package cn.huiyunche.base.service.interfaces.impl;

import cn.huiyunche.base.service.constant.QiniuConstant;
import cn.huiyunche.base.service.constant.WeixinConstant;
import cn.huiyunche.base.service.framework.utils.HYCUtils;
import cn.huiyunche.base.service.framework.utils.QiniuUtils;
import cn.huiyunche.base.service.framework.utils.WeixinUtils;
import cn.huiyunche.base.service.interfaces.QiniuService;
import cn.huiyunche.base.service.vo.QuniuResponseVo;
import cn.huiyunche.base.service.vo.Result;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import com.qiniu.util.StringUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class QiniuServiceImpl implements QiniuService {

    private static final Logger logger = LoggerFactory.getLogger(QiniuServiceImpl.class);

    public Result<String> getSimpleUploadToken() {
        Result<String> result = new Result<String>(true, null, null);
        result.setData(QiniuUtils.generateSimpleUploadTicket());
        return result;
    }

    public Result<String> getSimpleUploadTokenForBrandLogo() {
        Result<String> result = new Result<String>(true, null, null);
        result.setData(QiniuUtils.generateSimpleUploadTicket(QiniuConstant.QINIU_LOGO_BUCKET));
        return result;
    }

    public Result<String> getDownloadUrl(String key, String mode, String w, String h) {
        Result<String> result = new Result<String>(false, null, null);
        String treatMethod = "";
        if (!StringUtils.isNullOrEmpty(mode)) {
            if (!StringUtils.isNullOrEmpty(w)) {
                treatMethod = treatMethod + "/w/" + w;
            }
            if (!StringUtils.isNullOrEmpty(h)) {
                treatMethod = treatMethod + "/h/" + h;
            }
            if (!StringUtils.isNullOrEmpty(treatMethod)) {
                treatMethod = "?imageView2/" + mode + treatMethod;
            }
        }
        if (StringUtils.isNullOrEmpty(key)) {
            logger.error("七牛获取下载url，key为空");
            result.setMessage("key为空");
            return result;
        }
        result.setSuccess(true);
        result.setData(QiniuUtils.generateDownloadTicket(key, treatMethod));
        return result;
    }

    public Result<Object> upload2QiniuByWeixin(String mediaIds) {
        Result<Object> rm = new Result<Object>(true);
        List<QuniuResponseVo> imgKeyList = new ArrayList<QuniuResponseVo>();
        try {
            if (org.apache.commons.lang3.StringUtils.isNotBlank(mediaIds)) {
                String[] mediaIdArray = mediaIds.split(",");
                for (String media : mediaIdArray) {
                    // 获取文件url
                    String urlPath = "";
                    if (HYCUtils.getConstantPropertiesLoader().getProperty(WeixinConstant.WEIXIN_TYPE)
                            .equals(WeixinConstant.WEIXIN_QY_TYPE)) {
                        urlPath += HYCUtils.getConstantPropertiesLoader().getProperty(WeixinConstant.WEIXIN_QY_MEDIA_URL);
                    } else {
                        urlPath += HYCUtils.getConstantPropertiesLoader().getProperty(WeixinConstant.WEIXI_MEDIA_URL);
                    }
                    urlPath += WeixinUtils.getAccessToken() + "&media_id=" + media;
                    URL url = new URL(urlPath);
                    //打开链接
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    imgKeyList.add(QiniuUtils.upload(IOUtils.toByteArray(url), media));
                }
                rm.setData(imgKeyList);
                return rm;
            }
            rm.setSuccess(false);
        } catch (Exception e) {
            logger.error("上传七牛 upload2QiniuByWeixin {}", e);
            throw new BusinessException("上传失败!");
        }
        return rm;
    }

    @Override
    public String getDownloadBrandUrl(String key) {
        return QiniuUtils.generateDownloadTicket(HYCUtils.getConstantPropertiesLoader().getProperty(QiniuConstant.QINIU_LOGO_BUCKET), key, "", "", "");
    }

    @Override
    public void reNameQiniuImages(String name, String urlPath, HttpServletRequest request, HttpServletResponse response) {
        try {
            URL url = new URL(urlPath);
            //打开链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            response.setHeader("Content-Type", "image/jpeg");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(name, "UTF-8") + ".jpeg");
            IOUtils.copy(conn.getInputStream(), response.getOutputStream());
        } catch (Exception e) {

        }
    }

}
